package xyz.lne.researchgroupmanage.service.impl;

import cn.hutool.extra.expression.engine.rhino.RhinoEngine;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import xyz.lne.researchgroupmanage.controller.response.KeywordResponse;
import xyz.lne.researchgroupmanage.entity.Keyword;
import xyz.lne.researchgroupmanage.entity.KeywordResearchgroup;
import xyz.lne.researchgroupmanage.entity.ResearchGroup;
import xyz.lne.researchgroupmanage.exception.BadRequestException;
import xyz.lne.researchgroupmanage.mapper.KeywordMapper;
import xyz.lne.researchgroupmanage.mapper.KeywordResearchgroupMapper;
import xyz.lne.researchgroupmanage.mapper.ResearchgroupMapper;
import xyz.lne.researchgroupmanage.service.KeywordResearchgroupService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author team7
 * @since 2021-01-19
 */
@Service
public class KeywordResearchgroupServiceImpl extends ServiceImpl<KeywordResearchgroupMapper, KeywordResearchgroup> implements KeywordResearchgroupService {

    @Autowired
    private ResearchgroupMapper researchgroupMapper;

    @Autowired
    private KeywordResearchgroupMapper keywordResearchgroupMapper;

    @Autowired
    private KeywordMapper keywordMapper;

    @Override
    public Boolean insertKeyword(Integer keywordId, Integer researchGroupId) {
        QueryWrapper<Keyword> KWrapper=new QueryWrapper<>();
        KWrapper.eq("keyword_id", keywordId);

        QueryWrapper<ResearchGroup> RGWrapper=new QueryWrapper<>();
        RGWrapper.eq("researchgroup_id",researchGroupId);

        QueryWrapper<KeywordResearchgroup> KRGWrapper=new QueryWrapper<>();
        KRGWrapper.eq("keyword_id", keywordId)
                .eq("researchgroup_id",researchGroupId);

        if(keywordMapper.selectCount(KWrapper)==0 || researchgroupMapper.selectCount(RGWrapper)==0){
            //TODO:根据需求确定抛出异常或返回false
            Map<String, Object> e = new HashMap<>();
            e.put("课题组不存在或关键词不存在", null);
            throw new BadRequestException(e);
        }

        if(keywordResearchgroupMapper.selectCount(KRGWrapper)>0){
            //TODO:已有该条记录时确定适当的返回值
            return true;
        }
        keywordResearchgroupMapper.insert(new KeywordResearchgroup(keywordId,researchGroupId));

        return true;
    }


}
